package com.scse.bms.web.admin;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.scse.bms.domain.ThemeVO;
import com.scse.bms.domain.UserHeadImgVO;
import com.scse.bms.domain.UserVO;
import com.scse.bms.entity.FeedbackDO;
import com.scse.bms.entity.HeadImgDO;
import com.scse.bms.entity.ThemeDO;
import com.scse.bms.entity.TypeDO;
import com.scse.bms.mapper.HeadImgMapper;
import com.scse.bms.service.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @Title: AdminController
 * @Author: 吴赠禹
 * @Date: 2021/1/7 10:53
 * @Version: 1.0
 * @Description: 管理员Controller
 */

@Api("后台")
@Slf4j
@Controller
public class AdminController {

    @Autowired
    @Qualifier("adminService")
    private AdminService adminService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private ThemeService themeService;

    @Autowired
    private HeadImgService headImgService;

    @Autowired
    private SendEmailService sendEmailService;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private FeedbackService feedbackService;

    @GetMapping("/admin/login")
    public String toLogin() {
        return "/back/login";
    }


    /**
     * 管理员退出登录
     * @param session
     * @return
     */
    @GetMapping("/admin/logout")
    public String adminLogout(HttpSession session) {
        session.removeAttribute("loginUser");
        if (session.getAttribute("url") != null) {
            session.removeAttribute("url");
        }
        return "redirect:back/login";
    }

    @PostMapping("/admin/login")
    @ResponseBody
    public String adminLogin(@RequestBody UserVO userVO, HttpSession session) {
        log.info("[adminLogin] 管理员登录: " + userVO);
        // 这里要注意类型（因为与前台共用登录拦截器，所以需要保存同样类型（UserVO））
        UserVO admin = adminService.selectAdminUser(userVO.getUsername(), userVO.getPassword());
        if (ObjectUtil.isNotNull(admin)) {
            // 把登录成功的用户保存起来
            session.setAttribute("loginUser", admin);
            // 记住管理员的头像 TODO，在loginUser.src字段获取头像
            // UserHeadImgVO headImg = headImgService.getHeadImgVOByUserId(admin.getId());
            //session.setAttribute("headImg", admin.getSrc());

            // 登录成功重定向到admin.html，防止表单重复提交
            // return "redirect:/admin";
            return "pass";
        } else {
            // model.addAttribute("msg", "用户名或者密码不正确！");
            // 回到前台登录页面
            // return "/back/admin-login";
            return "fail";
        }
    }

    @PostMapping("/admin/updateUserPass")
    @ResponseBody
    public String updateUserPass(@RequestBody Map<String, String> map) {

        log.info(log.getClass().getSimpleName() + " [updateUserPass] data: " + map.toString());
        int res = adminService.updateUserPass(map);
        JSONObject json = new JSONObject();
        json.put("res", res);
        return json.toString();
    }

    @PostMapping("/admin/userValid")
    @ResponseBody
    public String updateUserValid(@RequestBody Map<String, Integer> map) {
        log.info(log.getClass().getSimpleName() + " [updateUserValid] ...");
        int res = adminService.updateUserValid(map);
        JSONObject json = new JSONObject();
        json.put("res", res);
        return json.toString();
    }


    /**
     * 去图书管理页面时，带上类型数据
     *
     * @param model
     * @return
     */
    @GetMapping("/admin/bookList")
    public String toBookListPage(Model model) {
        List<TypeDO> types = typeService.selectAll();
        List<ThemeVO> themes = themeService.list();
        model.addAttribute("types", types);
        model.addAttribute("themes", themes);
        return "/back/book/bookList";
    }


    @PostMapping("/admin/sendTempEmail")
    @ResponseBody
    public String sendEmail(@RequestBody FeedbackDO feedbackDO) {
        log.info("[sendEmail] 发送反馈邮件：" + feedbackDO);
        // 开始定制模板邮件内容
        Context context = new Context();
        context.setVariable("question", feedbackDO.getContent());
        context.setVariable("answer", feedbackDO.getReplyContent());
        // 使用TemplateEngine设置要处理的模板页面
        String emailContent = templateEngine.process("emailTemplate_feedback", context);
        sendEmailService.sendTemplateEmail(feedbackDO.getEmail(), "Beehive", emailContent);
        // 修改反馈状态
        boolean result = feedbackService.updateById(feedbackDO);
        log.info("[sendEmail] 设置反馈状态为已回复：" + result);
        // TODO 因为发送邮件服务的返回值为空，暂时指定返回true
        return "true";
    }

}
